/*
    Copyright © 2010  Ahti Legonkov
    
    This file is part of j+-.
    
    j+- is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
    
    j+- is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
    
    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package cx.ath.skyflyer.javapm.visitor;

import cx.ath.skyflyer.javapm.symbol.ScopeType;
import cx.ath.skyflyer.javapm.symbol.SymbolTable;
import japa.parser.JavaParser;
import japa.parser.ParseException;
import japa.parser.ast.BlockComment;
import japa.parser.ast.CompilationUnit;
import japa.parser.ast.ImportDeclaration;
import japa.parser.ast.LineComment;
import japa.parser.ast.PackageDeclaration;
import japa.parser.ast.TypeParameter;
import japa.parser.ast.body.AnnotationDeclaration;
import japa.parser.ast.body.AnnotationMemberDeclaration;
import japa.parser.ast.body.ClassOrInterfaceDeclaration;
import japa.parser.ast.body.ConstructorDeclaration;
import japa.parser.ast.body.DestructorDeclaration;
import japa.parser.ast.body.EmptyMemberDeclaration;
import japa.parser.ast.body.EmptyTypeDeclaration;
import japa.parser.ast.body.EnumConstantDeclaration;
import japa.parser.ast.body.EnumDeclaration;
import japa.parser.ast.body.FieldDeclaration;
import japa.parser.ast.body.InitializerDeclaration;
import japa.parser.ast.body.JavadocComment;
import japa.parser.ast.body.MethodDeclaration;
import japa.parser.ast.body.Parameter;
import japa.parser.ast.body.VariableDeclarator;
import japa.parser.ast.body.VariableDeclaratorId;
import japa.parser.ast.expr.ArrayAccessExpr;
import japa.parser.ast.expr.ArrayCreationExpr;
import japa.parser.ast.expr.ArrayInitializerExpr;
import japa.parser.ast.expr.AssignExpr;
import japa.parser.ast.expr.BinaryExpr;
import japa.parser.ast.expr.BooleanLiteralExpr;
import japa.parser.ast.expr.CastExpr;
import japa.parser.ast.expr.CharLiteralExpr;
import japa.parser.ast.expr.ClassExpr;
import japa.parser.ast.expr.ConditionalExpr;
import japa.parser.ast.expr.DoubleLiteralExpr;
import japa.parser.ast.expr.EnclosedExpr;
import japa.parser.ast.expr.FieldAccessExpr;
import japa.parser.ast.expr.InstanceOfExpr;
import japa.parser.ast.expr.IntegerLiteralExpr;
import japa.parser.ast.expr.IntegerLiteralMinValueExpr;
import japa.parser.ast.expr.LongLiteralExpr;
import japa.parser.ast.expr.LongLiteralMinValueExpr;
import japa.parser.ast.expr.MarkerAnnotationExpr;
import japa.parser.ast.expr.MemberValuePair;
import japa.parser.ast.expr.MethodCallExpr;
import japa.parser.ast.expr.NameExpr;
import japa.parser.ast.expr.NormalAnnotationExpr;
import japa.parser.ast.expr.NullLiteralExpr;
import japa.parser.ast.expr.ObjectCreationExpr;
import japa.parser.ast.expr.QualifiedNameExpr;
import japa.parser.ast.expr.SingleMemberAnnotationExpr;
import japa.parser.ast.expr.StringLiteralExpr;
import japa.parser.ast.expr.SuperExpr;
import japa.parser.ast.expr.ThisExpr;
import japa.parser.ast.expr.UnaryExpr;
import japa.parser.ast.expr.VariableDeclarationExpr;
import japa.parser.ast.stmt.AssertStmt;
import japa.parser.ast.stmt.BlockStmt;
import japa.parser.ast.stmt.BreakStmt;
import japa.parser.ast.stmt.CatchClause;
import japa.parser.ast.stmt.ContinueStmt;
import japa.parser.ast.stmt.DoStmt;
import japa.parser.ast.stmt.EmptyStmt;
import japa.parser.ast.stmt.ExplicitConstructorInvocationStmt;
import japa.parser.ast.stmt.ExpressionStmt;
import japa.parser.ast.stmt.ForStmt;
import japa.parser.ast.stmt.ForeachStmt;
import japa.parser.ast.stmt.IfStmt;
import japa.parser.ast.stmt.LabeledStmt;
import japa.parser.ast.stmt.ReturnStmt;
import japa.parser.ast.stmt.SwitchEntryStmt;
import japa.parser.ast.stmt.SwitchStmt;
import japa.parser.ast.stmt.SynchronizedStmt;
import japa.parser.ast.stmt.ThrowStmt;
import japa.parser.ast.stmt.TryStmt;
import japa.parser.ast.stmt.TypeDeclarationStmt;
import japa.parser.ast.stmt.WhileStmt;
import japa.parser.ast.type.ClassOrInterfaceType;
import japa.parser.ast.type.PrimitiveType;
import japa.parser.ast.type.ReferenceType;
import japa.parser.ast.type.VoidType;
import japa.parser.ast.type.WildcardType;
import japa.parser.ast.visitor.VoidVisitorAdapter;
import java.io.File;
import java.io.IOException;

/**
 * This visitor visits the AST and generates symbol tables. It generates a
 * symbol table per each scope.
 * @author Ahti Legonkov
 */
public class SymbolTableCreationVisitor extends VoidVisitorAdapter {

    private final String sourceFile;
    private final String sourceRoot;
    private final SymbolTable globalSymbolTable;
    private SymbolTable currentSymbolTable;
    private PackageDeclaration currentPackage;

    /**
     *
     * @param sourceRoot directory that contains the source packages.
     * @param sourceFile file path relative to sourceRoot.
     */
    public SymbolTableCreationVisitor(String sourceRoot, String sourceFile) {
        this(sourceRoot, sourceFile, new SymbolTable());
    }

    /**
     *
     * @param sourceRoot
     * @param sourceFile
     * @param globalSymbolTable
     */
    public SymbolTableCreationVisitor(String sourceRoot, String sourceFile, SymbolTable globalSymbolTable) {
        this.sourceFile = sourceFile;
        this.sourceRoot = sourceRoot;
        this.globalSymbolTable = globalSymbolTable;
        this.currentSymbolTable = globalSymbolTable;
    }

    ////////////////////////////////////////////////////////////////////////////
    // Constructs that create a new scope or add names to scope
    ////////////////////////////////////////////////////////////////////////////

    @Override
    public void visit(CompilationUnit n, Object arg) {
        //final SymbolTable prevSymbolTable = currentSymbolTable;
        //currentSymbolTable = new SymbolTable(prevSymbolTable, ScopeType.Package);
        n.setData(currentSymbolTable);
        super.visit(n, arg);
        //currentSymbolTable = prevSymbolTable;
    }

    @Override
    public void visit(BlockStmt n, Object arg) {
        final SymbolTable prevSymbolTable = currentSymbolTable;
        currentSymbolTable = new SymbolTable(prevSymbolTable, ScopeType.Local);
        n.setData(currentSymbolTable);
        super.visit(n, arg);
        currentSymbolTable = prevSymbolTable;
    }

    @Override
    public void visit(ClassOrInterfaceDeclaration n, Object arg) {
        currentSymbolTable.put(n.getName(), n);

        final SymbolTable prevSymbolTable = currentSymbolTable;
        currentSymbolTable = new SymbolTable(prevSymbolTable, ScopeType.Class);
        n.setData(currentSymbolTable);
        super.visit(n, arg);
        currentSymbolTable = prevSymbolTable;
    }

    @Override
    public void visit(ClassOrInterfaceType n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(ConstructorDeclaration n, Object arg) {
        currentSymbolTable.put(n.getName(), n);

        final SymbolTable prevSymbolTable = currentSymbolTable;
        currentSymbolTable = new SymbolTable(prevSymbolTable, ScopeType.Method);
        n.setData(currentSymbolTable);
        if (n.getParameters() != null) {
            for (Parameter param : n.getParameters()) {
                currentSymbolTable.put(param.getId().getName(), param);
            }
        }
        super.visit(n, arg);
        currentSymbolTable = prevSymbolTable;
    }

    @Override
    public void visit(EnumDeclaration n, Object arg) {
        currentSymbolTable.put(n.getName(), n);
        
        final SymbolTable prevSymbolTable = currentSymbolTable;
        currentSymbolTable = new SymbolTable(prevSymbolTable, ScopeType.Class);
        n.setData(currentSymbolTable);
        super.visit(n, arg);
        currentSymbolTable = prevSymbolTable;
    }

    @Override
    public void visit(FieldDeclaration n, Object arg) {
        n.setData(currentSymbolTable);
        for (VariableDeclarator var : n.getVariables()) {
            currentSymbolTable.put(var.getId().getName(), n);
        }
        super.visit(n, arg);
    }

    @Override
    public void visit(MethodDeclaration n, Object arg) {
        currentSymbolTable.put(n.getName(), n);

        final SymbolTable prevSymbolTable = currentSymbolTable;
        currentSymbolTable = new SymbolTable(prevSymbolTable, ScopeType.Method);
        if (n.getParameters() != null) {
            for (Parameter param : n.getParameters()) {
                currentSymbolTable.put(param.getId().getName(), param);
            }
        }
        n.setData(currentSymbolTable);
        super.visit(n, arg);
        currentSymbolTable = prevSymbolTable;
    }

    @Override
    public void visit(VariableDeclarationExpr n, Object arg) {
        n.setData(currentSymbolTable);
        for (VariableDeclarator var : n.getVars()) {
            currentSymbolTable.put(var.getId().getName(), n);
        }
        super.visit(n, arg);
    }

    @Override
    public void visit(EnumConstantDeclaration n, Object arg) {
        currentSymbolTable.put(n.getName(), n);
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(ForeachStmt n, Object arg) {
        final SymbolTable prevSymbolTable = currentSymbolTable;
        currentSymbolTable = new SymbolTable(prevSymbolTable, ScopeType.Local);
        n.setData(currentSymbolTable);
        super.visit(n, arg);
        currentSymbolTable = prevSymbolTable;
    }

    @Override
    public void visit(ForStmt n, Object arg) {
        final SymbolTable prevSymbolTable = currentSymbolTable;
        currentSymbolTable = new SymbolTable(prevSymbolTable, ScopeType.Local);
        n.setData(currentSymbolTable);
        super.visit(n, arg);
        currentSymbolTable = prevSymbolTable;
    }

    @Override
    public void visit(LabeledStmt n, Object arg) {
        currentSymbolTable.put(n.getLabel(), n);
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    ///////////////////////////////////////////////////////////////////////////
    // There is nothing interesting beyond this line!
    ///////////////////////////////////////////////////////////////////////////

    @Override
    public void visit(AnnotationDeclaration n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(AnnotationMemberDeclaration n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(ArrayAccessExpr n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(ArrayCreationExpr n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(ArrayInitializerExpr n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(AssertStmt n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(AssignExpr n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(BinaryExpr n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(BlockComment n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(BooleanLiteralExpr n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(BreakStmt n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(CastExpr n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(CatchClause n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(CharLiteralExpr n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(ClassExpr n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(ConditionalExpr n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(DestructorDeclaration n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(ContinueStmt n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(DoStmt n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(DoubleLiteralExpr n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(EmptyMemberDeclaration n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(EmptyStmt n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(EmptyTypeDeclaration n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(EnclosedExpr n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(ExplicitConstructorInvocationStmt n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(ExpressionStmt n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(FieldAccessExpr n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(IfStmt n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    /**
     * Load a class
     * @param className
     * @return true if class is successfully loaded.
     */
    private boolean loadClass(NameExpr className) {
        final String fileName = className.toString().replace(".", File.separator);
        final String filePath = sourceRoot + fileName + ".jpm";
        try {
            final File file = new File(filePath);
            CompilationUnit cu = JavaParser.parse(file);
            PrivateSymbolStripVisitor pssv = new PrivateSymbolStripVisitor();
            pssv.visit(cu, null);

            SymbolTableCreationVisitor stcv = new SymbolTableCreationVisitor(sourceRoot, filePath, globalSymbolTable);
            stcv.visit(cu, null);

            ClassOrInterfaceDeclaration cls = globalSymbolTable.getClass(className.getName());
            if (cls == null) {
                // messages.addError("file does not contain class");
                return false;
            }
        }
        catch (IOException ex) {
            return false;
        }
        catch (ParseException ex) {
            return false;
        }

        return true;
    }

    @Override
    public void visit(ImportDeclaration n, Object arg) {
        n.setData(currentSymbolTable);
        currentSymbolTable.put(n.getName().getName(), n);
        n.getName().accept(this, arg);
    }

    @Override
    public void visit(InitializerDeclaration n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(InstanceOfExpr n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(IntegerLiteralExpr n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(IntegerLiteralMinValueExpr n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(JavadocComment n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(LineComment n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(LongLiteralExpr n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(LongLiteralMinValueExpr n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(MarkerAnnotationExpr n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(MemberValuePair n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(MethodCallExpr n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    private void visitNameExpr(NameExpr n, Object arg) {
        if (currentPackage != null) {

            // It's a package declaration, this means that the name is a package name.

            // There is no need to restore symbol table afterwards.

            final PackageDeclaration pkg = new PackageDeclaration(n);
            pkg.setBeginLine(n.getBeginLine());
            pkg.setBeginColumn(n.getBeginColumn());
            pkg.setData(currentSymbolTable);
            n.setData(currentSymbolTable);
            currentSymbolTable.put(n.getName(), pkg);

            currentSymbolTable = new SymbolTable(currentSymbolTable, ScopeType.Package);
            currentPackage.setData(currentSymbolTable);
        }
        else {
            n.setData(currentSymbolTable);
        }
        
        super.visit(n, arg);
    }

    @Override
    public void visit(NameExpr n, Object arg) {
        visitNameExpr(n, arg);
    }

    @Override
    public void visit(QualifiedNameExpr n, Object arg) {
        n.getQualifier().accept(this, arg);
        visitNameExpr(n, arg);
    }

    @Override
    public void visit(NormalAnnotationExpr n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(NullLiteralExpr n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(ObjectCreationExpr n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(PackageDeclaration n, Object arg) {
        final PackageDeclaration prevPackage = currentPackage;
        currentPackage = n;
        n.setData(currentSymbolTable);
        n.getName().accept(this, arg);
        currentPackage = prevPackage;
    }

    @Override
    public void visit(Parameter n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(PrimitiveType n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(ReferenceType n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(ReturnStmt n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(SingleMemberAnnotationExpr n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(StringLiteralExpr n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(SuperExpr n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(SwitchEntryStmt n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(SwitchStmt n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(SynchronizedStmt n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(ThisExpr n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(ThrowStmt n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(TryStmt n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(TypeDeclarationStmt n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(TypeParameter n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(UnaryExpr n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(VariableDeclarator n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(VariableDeclaratorId n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(VoidType n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(WhileStmt n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }

    @Override
    public void visit(WildcardType n, Object arg) {
        n.setData(currentSymbolTable);
        super.visit(n, arg);
    }
}
